package com.guardian.communication;

import org.apache.commons.io.IOUtils;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

/**
 * 通讯客户端
 * @author: huwei
 * @date: 2019/10/11 15:59
 * @version: 1.0.0
 */
public interface CommunicationClient {

    /**
     * 发送消息
     * @param host 目标服务ip地址
     * @param port 目标服务端口号
     * @param message 发送消息
     * @return 返回消息
     * @throws IOException 异常
     */
    default String sendMessage(String host ,int port ,String message) throws IOException {
        Socket socket = new Socket(host ,port);
        OutputStream os = socket.getOutputStream();
        os.write(message.getBytes());
        os.flush();

        InputStream is = socket.getInputStream();
        byte[] buf = new byte[1024 * 8];
        int size = is.read(buf);
        socket.close();

        byte[] realDataBuf = new byte[size];
        System.arraycopy(buf ,0 ,realDataBuf ,0 ,size);
        return new String(realDataBuf);
    }
}
